package com.panda.pandawash.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

import com.panda.pandawash.bean.DownloadTask;
import com.panda.pandawash.bean.NotificationBean;
import com.panda.pandawash.util.DownloadUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;



public class DownloadServices extends Service {
    private Context mContext = this;
    private final int DOWN_LOADING = 0;
    private final int DOWN_COMPLETE = 1;
    private final int DOWN_ERR = 2;
    private final int TIMER_PERIOD = 1500;
    protected Timer mTimer;
    protected NotificationManager mNotificationManager;
    protected Map<String, DownloadTask> map_downloadtask;

    public DownloadServices() {
    }

    public IBinder onBind(Intent intent) {
        return null;
    }

    public void onDestroy() {
        super.onDestroy();
    }

    public void onCreate() {
        super.onCreate();
        this.mTimer = new Timer();
        this.mNotificationManager = (NotificationManager)this.getSystemService("notification");
        this.map_downloadtask = new HashMap();
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        String mUrl = intent.getExtras().getString("url");
        int mNotifyId = intent.getExtras().getInt("notifyId");
        NotificationBean mNotification = new NotificationBean(this, 2130837547, "开始下载", System.currentTimeMillis());
        System.out.println("NotifyId = " + mNotifyId);
        if(this.map_downloadtask.containsKey(mUrl)) {
            Toast.makeText(this.mContext, "已存在此下载任务", 0).show();
        } else {
            DownloadTask mDownloadTask = new DownloadTask();
            mDownloadTask.setUrl(mUrl);
            mDownloadTask.setNotifyID(mNotifyId);
            mDownloadTask.setNotification(mNotification);
            this.map_downloadtask.put(mUrl, mDownloadTask);
            MyRunnable mRunnable = new MyRunnable(mDownloadTask);
            (new Thread(mRunnable)).start();
        }

        return super.onStartCommand(intent, flags, startId);
    }

    class MyHandler extends Handler {
        private DownloadUtil mDownUtil;

        public MyHandler(DownloadUtil downUtil) {
            this.mDownUtil = downUtil;
        }

        public void handleMessage(Message msg) {
            switch(msg.what) {
                case 0:
                    ((Notification)msg.obj).contentView.setProgressBar(2131296421, 100, msg.arg1, false);
                    ((Notification)msg.obj).contentView.setTextViewText(2131296271, "下载" + msg.arg1 + "%");
                    DownloadServices.this.mNotificationManager.notify(msg.arg2, (Notification)msg.obj);
                    System.out.println("DOWN_LOADING --> mNotifyId --> " + msg.arg2 + " --> " + msg.arg1 + "%");
                    break;
                case 1:
                    this.removeMessages(0);
                    Toast.makeText(DownloadServices.this.mContext, "下载完成", 0).show();
                    this.mDownUtil.installApk(DownloadServices.this.mContext, (File)msg.obj);
                    System.out.println("======================DOWN_COMPLETE================================");
                    this.stopService();
                    break;
                case 2:
                    this.removeMessages(0);
                    DownloadServices.this.map_downloadtask.remove(((DownloadTask)msg.obj).getUrl());
                    Toast.makeText(DownloadServices.this.mContext, "下载失败", 0).show();
                    this.stopService();
            }

        }

        private void stopService() {
            if(DownloadServices.this.map_downloadtask.isEmpty()) {
                DownloadServices.this.stopSelf(-1);
            }

        }
    }

    class MyRunnable implements Runnable {
        private DownloadUtil mDownUtil = new DownloadUtil();
        private DownloadTask mDownTask;
        private Handler mHandler;
        private TimerTask mTimerTask;

        public MyRunnable(DownloadTask downTask) {
            this.mDownTask = downTask;
            this.mHandler = DownloadServices.this.new MyHandler(this.mDownUtil);
            this.mTimerTask = DownloadServices.this.new MyTimerTask(this.mDownUtil, this.mHandler, this.mDownTask);
        }

        public void run() {
            DownloadServices.this.mTimer.schedule(this.mTimerTask, 0L, 1500L);
            this.mDownUtil.downloadFile(this.mDownTask.getUrl());
        }
    }

    class MyTimerTask extends TimerTask {
        private Handler mHandler;
        private DownloadUtil mDownUtil;
        private DownloadTask mDownTask;
        private DownloadUtil.IOnDownloadListener mListener;

        public MyTimerTask(DownloadUtil downUtil, Handler handler, DownloadTask downTask) {
            this.mHandler = handler;
            this.mDownUtil = downUtil;
            this.mDownTask = downTask;
            this.mListener = new DownloadUtil.IOnDownloadListener() {
                public void updateNotification(int progress, int totalSize, File downFile) {
                    boolean rate = false;
                    if(totalSize > 0) {
                        int rate1 = progress * 100 / totalSize;
                        MyTimerTask.this.mHandler.obtainMessage(0, rate1, MyTimerTask.this.mDownTask.getNotifyID(), MyTimerTask.this.mDownTask.getNotification()).sendToTarget();
                    } else if(totalSize == 0) {
                        MyTimerTask.this.mHandler.obtainMessage(0, 0, MyTimerTask.this.mDownTask.getNotifyID(), MyTimerTask.this.mDownTask.getNotification()).sendToTarget();
                    } else {
                        MyTimerTask.this.cancel();
                        MyTimerTask.this.mHandler.obtainMessage(2, MyTimerTask.this.mDownTask).sendToTarget();
                    }

                    if(totalSize > 0 && downFile != null && totalSize == (int)downFile.length()) {
                        MyTimerTask.this.cancel();
                        MyTimerTask.this.mHandler.obtainMessage(1, downFile).sendToTarget();
                        map_downloadtask.remove(MyTimerTask.this.mDownTask.getUrl());
                        System.out.println("DOWN_COMPLETE ==> totalSize ==> " + totalSize);
                    }

                }
            };
        }

        public void run() {
            this.mDownUtil.setOnDownloadListener(this.mListener);
        }
    }
}
